package com.zwr.sheller.shop.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 配置Redis的序列化器
 * 只要这个类被Spring管理，在其他地方自动注入RedisTemplate时就会自动的采用该类的序列化方式
 *
 * @Author LSY
 * @Date 2021/11/25 10:41
 * @Version 1.0
 **/
@Configuration
public class RedisConfiguration {

    // 获得RedisTemplate的方法，操作redis的主体对象
    // 需要指定其key和value的泛型，key都是String，value有数种，故要用Object
    @Bean(value = "template")
    public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 实例化jackson2序列化器，并配置
        @SuppressWarnings("rawtypes")
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        // 其余的value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);

        // 实例化jackson2序列化器，并配置
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }
}
